package com.bilibili.servlet;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.bilibili.entity.CommonResult;
import com.bilibili.entity.User;
import com.bilibili.service.UserService;
import com.bilibili.service.impl.UserServiceImpl;

@SuppressWarnings("serial")//抑制serialVersionUID字段警告
@MultipartConfig
@WebServlet("/updateHeadImg")
public class UpdateHeadImgServlet extends HttpServlet {
	
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	
    	response.setContentType("application/json; charset=utf-8");
    	// 2. 获取上传者id
    	int user_id = ((User) request.getSession().getAttribute("loginUser")).getUserId();
        // 2. 获取上传文件
		CommonResult cr = new CommonResult();
        Part filePart = request.getPart("file");
        if (filePart == null || filePart.getSize() == 0) {
			cr.setCode(409);
			cr.setMassage("请正确上传文件");
			response.getWriter().write(cr.toJSONString());
            return;
        }else {
        	if(filePart.getSize() > 2*1024*1024) {
    			cr.setCode(409);
    			cr.setMassage("图片大小不能大于2M");
    			response.getWriter().write(cr.toJSONString());
                return;
        	}else if(!filePart.getContentType().contains("image")){
        		cr.setCode(409);
    			cr.setMassage("图片格式应该为图片");
    			response.getWriter().write(cr.toJSONString());
				return;
			}
        }

        // 3. 处理文件名
        String originalFilename = "";
        String contentDisp = filePart.getHeader("content-disposition");
        for (String content : contentDisp.split(";")) {
            if (content.trim().startsWith("filename")) {
            	originalFilename = content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString();
        String saveFileName = uuid + fileExtension;

        // 4. 保存文件到服务器
        String uploadPath = "C:/material/img/avatar/"+saveFileName;
        filePart.write(uploadPath);

        // 5. 构建访问路径（假设通过虚拟目录访问）
        String visitPath = "/bilibili/material/img/avatar/" + saveFileName;

        // 6. 更新用户信息
        User user = new User();
        user.setUserId(user_id);
        user.setAvatarUrl(visitPath);
        
        UserService userService = new UserServiceImpl();
        
        // 7. 删除旧头像
        String oldHeadImg = userService.queryUserByUserId(user_id).getAvatarUrl();
        if (userService.updataHeadImg(user)) {
        	String[] oldImgs = oldHeadImg.split("/");
			String oldImg = oldImgs[oldImgs.length-1];
			if(!oldImg.equals("default.jpg")) {
				File file = new File("C:/material/img/avatar/"+oldImg);
				if(file.exists()) {
					file.delete();
				}
			}
			cr.setCode(200);
			response.getWriter().write(cr.toJSONString());
        } else {
        	String[] oldImgs = visitPath.split("/");
			String oldImg = oldImgs[oldImgs.length-1];
			File file = new File("C:/material/img/avatar/"+oldImg);
			if(file.exists()) {
				file.delete();
			}
			cr.setCode(409);
			response.getWriter().write(cr.toJSONString());
        }
    }
}